package http;

import frame.service.standard.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 保底的异常处理器
 * */
@ControllerAdvice
public class DefaultErrorHandle {
    private MiayViewResolver viewResolver;

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Map<String, Object> errorHandle(Exception e, HttpServletRequest request, HttpServletResponse response){
        String viewName = null;
        String header = request.getHeader(HttpHeaders.CONTENT_TYPE);
        if(header!=null){
            MediaType mediaType = MediaType.parseMediaType(header);
            viewName = mediaType.getType()+"/"+mediaType.getSubtype();
        }else{
            viewName = Constants.DEFAULT_SERVICE_HANDLE;
        }
        Map<String, Object> data = new HashMap<>();
        data.put(Constants.RESPONSE_MSG_CONTENT, e.getMessage());
        return viewResolver.createModel(viewName, data, "999999", e.getMessage(), null);
    }

    @Autowired
    public void setViewResolver(MiayViewResolver viewResolver) {
        this.viewResolver = viewResolver;
    }
}
